<template>
  <div class="app-container">

    <div style="margin-left:20px">
      <el-form ref="queryForm" label-position="left" label-width="70px" inline size="small" >
        <el-form-item label="" >
          <el-input v-model="queryInfo" style="width: 300px;" placeholder="输入名称搜索" @keyup.enter.native="queryClick"/>
        </el-form-item>
        <el-form-item label="" >
          <el-button type="primary" @click="queryClick">查询</el-button>
          <el-button type="primary" @click="handleAddCRUD">生成增删改查操作</el-button>
        </el-form-item>
      </el-form>
    </div>

    <data-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      :border="false"
      :stripe="true"
      :url="url"
      size="small"
      style="width: 100%;"
      @filter-change="handleFilterChange">

      <!-- <el-table-column label="编号" prop="OperateID" align="center" width="100px"/> -->
      <el-table-column label="序号" prop="Sequence" align="center" width="80px"/>
      <el-table-column label="操作名称" prop="OperateName" align="center" />
      <el-table-column label="操作类别" prop="OperateType" align="center" width="80px" >
        <template slot-scope="scope" >
          <span>{{ scope.row.OperateType|operateTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="控制器" prop="Controller" align="center" width="100px" />
      <el-table-column label="方法" prop="Action" align="center" min-width="100px" />
      <el-table-column :filters="actionTypeFilters" label="请求方式" prop="Method" filter-placement="bottom" column-key="Method" align="center" width="80px">
        <template slot-scope="scope" >
          <span>{{ scope.row.Method }}</span>
        </template>
      </el-table-column>
      <el-table-column :filters="accessLevelFilters" label="访问级别" prop="AccessLevel" filter-placement="bottom" column-key="AccessLevel" align="center" width="100px">
        <template slot-scope="scope" >
          <span>{{ scope.row.AccessLevel|accessLevelFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="canEdit" label="操作" align="center" width="100px" class-name="small-padding fixed-width" >
        <template slot="header" slot-scope="scope">
          <el-button v-if="canAdd" type="text" size="mini" @click="handleCreate">添加</el-button>
          <template v-else>{{ scope.column.label }}</template>
        </template>
        <template slot-scope="scope" >
          <el-button v-if="canUpdate" type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <confirm-poptip v-if="canDelete" type="text" size="mini" @on-ok="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </data-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" size="small" >
        <el-row>
          <el-col :span="12"/>
          <el-col :span="12"/>
        </el-row>
        <el-form-item label="序号" prop="Sequence">
          <el-input-number :precision="0" :min="1" v-model="temp.Sequence"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作名称" prop="OperateName">
              <el-input v-model="temp.OperateName" :maxlength="50"/>
          </el-form-item></el-col>
          <el-col :span="12">
            <el-form-item label="操作类别" prop="OperateType">
              <el-select v-model="temp.OperateType" filterable clearable class="filter-item" style="width:100%">
                <el-option v-for="item in operateTypeFilters" :key="item.value" :label="item.text" :value="item.value"/>
              </el-select>
          </el-form-item></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请求方式" prop="Method">
              <el-select v-model="temp.Method" filterable class="filter-item" style="width:100%">
                <el-option v-for="item in actionTypeFilters" :key="item.value" :label="item.text" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问级别" prop="AccessLevel">
              <el-select v-model="temp.AccessLevel" filterable class="filter-item" style="width:100%">
                <el-option v-for="item in accessLevelFilters" :key="item.value" :label="item.text" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="控制器" prop="Controller">
              <el-input v-model="temp.Controller" :maxlength="500" placeholder="不填写使用模块控制器"/>
            </el-form-item>
          </el-col>
          <el-col :span="12"/>
        </el-row>
        <el-form-item label="方法" prop="Action">
          <el-input v-model="temp.Action" :maxlength="500" placeholder="多个方法请用;分割" type="textarea"/>
        </el-form-item>
        <el-form-item label="URL" prop="URL">
          <el-input v-model="temp.URL" :maxlength="500" type="textarea"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" :loading="okloading" type="primary" @click="createData">确 定</el-button>
        <el-button v-else :loading="okloading" type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, getInfo, add, update, remove, addCRUD } from '@/api/operate'
import waves from '@/directive/waves' // 水波纹指令
import { canAdd, canUpdate, canDelete } from '@/utils'

const operateTypeOptions = [
  { text: '添加', value: 'create' },
  { text: '修改', value: 'update' },
  { text: '删除', value: 'delete' },
  { text: '审核', value: 'verify' }
]
const actionOptions = [
  { text: 'get', value: 'get' },
  { text: 'post', value: 'post' },
  { text: 'put', value: 'put' },
  { text: 'delete', value: 'delete' }
]
const accessLevelOptions = [
  { text: '完全访问', value: 0 },
  { text: '登录访问', value: 1 },
  { text: '需要设置访问', value: 2 }
]

const accessLevelKeyValue = accessLevelOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.text
  return acc
}, {})

const operateTypeKeyValue = operateTypeOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.text
  return acc
}, {})

export default {
  name: 'Operate',
  directives: {
    waves
  },
  filters: {
    accessLevelFilter(type) {
      return accessLevelKeyValue[type]
    },
    operateTypeFilter(type) {
      return operateTypeKeyValue[type]
    }
  },
  props: {
    moduleId: {
      type: Number,
      default: null
    },
    defaultController: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      controllerName: 'Operate',
      // url: '/operate/list',
      okloading: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        moduleId: null,
        page: 1,
        limit: 15,
        filters: []
      },
      operateTypeFilters: operateTypeOptions,
      actionTypeFilters: actionOptions,
      accessLevelFilters: accessLevelOptions,
      queryInfo: null,
      temp: {
        MouduleID: null,
        OperateName: null,
        Controller: null,
        Action: null,
        Method: null,
        URL: null,
        AccessLevel: null,
        Sequence: null
      },
      filters: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      rules: {
        OperateName: { required: true, message: '不能为空' },
        Controller: { required: false, message: '不能为空' },
        Action: { required: false, message: '不能为空' },
        Method: { required: true, message: '不能为空' },
        URL: { required: false, message: '不能为空' },
        AccessLevel: { required: true, message: '不能为空' },
        Sequence: { required: true, message: '不能为空' }
      }
    }
  },
  computed: {
    url() {
      return '/operate/list?moduleId=' + this.moduleId
    },
    canEdit() {
      return this.canAdd || this.canUpdate || this.canDelete
    },
    canAdd() {
      return canAdd(this.$store.state, this.controllerName)
    },
    canUpdate() {
      return canUpdate(this.$store.state, this.controllerName)
    },
    canDelete() {
      return canDelete(this.$store.state, this.controllerName)
    }
  },
  watch: {
  },
  created() {
    this.getList()
  },
  methods: {

    handleFilterChange(filters) {
      let row = null
      let val = null
      for (const i in filters) {
        row = i
        val = filters[i]
      }
      const filter = [{
        row: row,
        op: 'contains',
        value: val
      }]
      this.setFilter(filter)
    },

    setFilter(filters) {
      for (const i in filters) {
        let filter = null
        for (const j in this.filters) {
          if (filters[i]['row'] === this.filters[j]['row']) {
            filter = this.filters[j]
          }
        }
        if (filter == null) {
          this.filters.push({ 'row': filters[i].row, 'op': filters[i].op, 'value': filters[i].value })
        } else {
          filter.value = filters[i].value
          filter.op = filters[i].op
        }
      }

      this.listQuery.page = 1
      this.getList()
    },

    getList() {
      this.listLoading = true
      const filters = []
      for (const i in this.filters) {
        if (this.filters[i].value && this.filters[i].value.length > 0) {
          filters.push({ 'field': this.filters[i].row, 'op': this.filters[i].op, 'value': this.filters[i].value })
        }
      }
      if (filters.length > 0) {
        this.listQuery.filters = JSON.stringify(filters)
      } else {
        this.listQuery.filters = null
      }
      this.listQuery.query = this.queryInfo
      this.listQuery.moduleId = this.moduleId
      if (this.moduleId) {
        getList(this.listQuery).then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },

    queryClick() {
      this.listQuery.page = 1
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        MouduleID: this.moduleId,
        OperateName: null,
        // Controller: this.defaultController,
        Controller: null,
        Action: null,
        Method: null,
        URL: null,
        AccessLevel: null,
        Sequence: null
      }
    },
    handleAddCRUD() {
      addCRUD(this.moduleId).then(() => {
        this.$notify({
          message: '生成成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.okloading = true
          const mytemp = Object.assign({}, this.temp)
          mytemp.moduleId = this.moduleId
          add(mytemp).then((response) => {
            this.okloading = false
            if (response.data) {
              const mydata = response.data
              this.temp = mydata
            }
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleUpdate(row) {
      const mydata = Object.assign({}, row)
      this.temp = mydata
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      getInfo(row.OperateID).then((response) => {
        if (response.success) {
          const data = response.data
          this.temp = Object.assign({}, data)

          for (const v of this.list) {
            if (v.OperateID === data.OperateID) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, data)
              break
            }
          }
        }
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.okloading = true
          const mytemp = Object.assign({}, this.temp)
          update(mytemp).then((response) => {
            this.okloading = false
            if (response.data) {
              const mydata = response.data
              this.temp = mydata
            }
            for (const v of this.list) {
              if (v.OperateID === this.temp.OperateID) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.okloading = false
          })
        }
      })
    },
    handleDelete(row) {
      remove(row.OperateID).then((response) => {
        if (response.success) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        }
      })
    }

  }
}

</script>
